package com.ease.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * 如果并发量请求很大，1万、十万，会有什么问题？OOM
 *
 * @author: chenhs
 * @date: Created in 11:00 2019/12/23
 **/
public class BIOServerV2 {

    private static Charset charset = Charset.forName("UTF-8");

    public static void main(String[] args) {
        int port = 9010;
        try (ServerSocket ss = new ServerSocket(port)) {
            while (true) {
                // 接收连接（阻塞-等待连接）
                Socket socket = ss.accept();
                //开启一个线程去处理这个连接
                new Thread(new SocketProcess(socket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    static class SocketProcess implements Runnable {

        Socket socket;

        public SocketProcess(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), charset))) {
                String mess;
                // 读取数据（阻塞-等待数据读取）
                while ((mess = reader.readLine()) != null) {
                    System.out.println(mess);
                }
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
